<template>
  <div class="main-container-content">
    <div class="tableBar">
      <div>
        <el-input class="condition-item" v-model="listState.queryWrapper.keyword" placeholder="请填写菜品名称..." style="width: 25%" />

        <el-select class="condition-item" v-model="listState.queryWrapper.dishCategoryId" style="width: 16%" placeholder=" --菜品分类--">
          <el-option key="1" label="--分类--" :value="null" />
          <el-option v-for="item in listState.shopDishCategoryList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>

        <el-select class="condition-item" v-model="listState.queryWrapper.dishStatus" style="width: 14%" placeholder="--状态--">
          <el-option key="1" label="--状态--" :value="null" />
          <el-option key="1" label="启售" :value="1" />
          <el-option key="0" label="禁售" :value="0" />
        </el-select>
        <el-button class="normal-btn" :icon="Search" @click="refreshList"> 查询 </el-button>
      </div>
      <div class="tableLab">
        <el-popconfirm title="确认要删除选择的菜品吗？" @confirm="batchDelete(listState.multiSelectIds)">
          <template #reference>
            <el-button class="delBut non" :style="{ display: !isViewPriorityDisplay ? 'block' : 'none' }">批量删除</el-button>
          </template>
        </el-popconfirm>
        <el-button style="margin-left: 15px" :icon="StarFilled" @click="isViewPriorityDisplay = !isViewPriorityDisplay"
          >{{ isViewPriorityDisplay ? '隐藏优先展示' : '查看优先展示' }}
        </el-button>
        <el-button class="baseBut" style="margin-left: 15px" :icon="Plus" @click="addOrEditDish(null)">新建菜品 </el-button>
      </div>
    </div>
    <el-table :data="listState.dishList" stripe class="tableBox" @selection-change="selectionChange">
      <el-table-column type="selection" width="25" v-if="!isViewPriorityDisplay" />
      <el-table-column prop="betterDisplay" label="优先展示" v-else>
        <template v-slot="{ row }">
          <el-switch
            v-model="row.betterDisplay"
            @change="changeBetterDisplay(row)"
            :active-value="1"
            :inactive-value="0"
            inline-prompt
            :active-icon="Check"
            :inactive-icon="Close"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="菜品名称" />
      <el-table-column prop="image" label="图片">
        <template v-slot="{ row }">
          <el-image style="width: 80px; height: 40px; border: none; cursor: pointer" :src="row.image">
            <template #error>
              <div class="image-slot">
                <img src="@/assets/image/noImg.png" style="width: auto; height: 40px; border: none" />
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="dishCategoryId" label="菜品分类">
        <template v-slot="scope">{{ findDishCategoryNameById(scope.row.dishCategoryId) }}</template>
      </el-table-column>
      <el-table-column label="售价">
        <template v-slot="scope">
          <span style="margin-right: 10px">￥{{ (scope.row.nowPrice.toFixed(2) * 100) / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售卖状态">
        <template v-slot="scope">
          <div class="tableColumn-status" :class="{ 'stop-use': String(scope.row.status) === '0' }">
            <span style="color: #13ce66" v-if="scope.row.status === 1">● 启售</span>
            <span style="color: #3d3d3d" v-else>● 停售</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后操作时间" />
      <el-table-column label="操作" width="250" align="center">
        <template v-slot="scope">
          <el-button :link="true" size="small" class="blueBug" @click="addOrEditDish(scope.row.id)" :icon="Edit"> 修改 </el-button>
          <el-popconfirm title="确认要删除该菜品吗？" @confirm="batchDelete([scope.row.id])">
            <template #reference>
              <el-button :link="true" size="small" :icon="Delete" class="delBut"> 删除 </el-button>
            </template>
          </el-popconfirm>
          <el-button
            :link="true"
            size="small"
            class="non"
            :class="{
              blueBug: scope.row.status === 1,
              delBut: scope.row.status !== 0
            }"
            @click="changeStatus(scope.row.id, scope.row.status == 1 ? 0 : 1)"
          >
            {{ scope.row.status === 0 ? '启售' : '停售' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="listState.total"
      :page-size="listState.queryWrapper.pageSize"
      small
      class="pagination"
    />
  </div>
</template>

<script setup lang="ts">
import { Check, Delete, Edit, Plus, Search, Close, StarFilled } from '@element-plus/icons-vue'
import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
import DishCategory from '@/types/entity/DishCategory'
import ComponentHat from '@/plugins/type'
import { DishPageWrapper } from '@/types/param/dish'
import Dish from '@/types/entity/Dish'
import router from '@/router'
import BetterDisplayStatus from '@/enums/BetterDisplayStatus'
const { $store, $API, $modal } = <ComponentHat>getCurrentInstance().proxy
const listState = reactive({
  shopDishCategoryList: [] as DishCategory[],
  dishList: [] as Dish[],
  total: 0,
  queryWrapper: {
    dishCategoryId: null,
    dishStatus: null,
    keyword: null,
    currentPage: 1,
    pageSize: 10
  } as DishPageWrapper,
  multiSelectIds: [] as number[]
})

// 初始化店铺分类数据
$API.dishCategory.listShopDishCategory().then((result) => {
  listState.shopDishCategoryList = result.data
})
// 刷新列表
async function refreshList() {
  const result = await $API.dish.queryShopDishListPage(listState.queryWrapper)
  if (result.success) {
    listState.dishList = result.data.listData
    listState.total = result.data.total
  }
}
// 初始化列表数据
refreshList()

// 根据dishCategoryId从dishCategory列表中查找对应的分类名称
function findDishCategoryNameById(dishCategoryId: number): string {
  const dishCategory: DishCategory = listState.shopDishCategoryList.find((dishCategory) => dishCategory.id == dishCategoryId)
  return dishCategory == null ? '' : dishCategory.name
}
// 点击了菜品的改变状态的按钮
async function changeStatus(dishId: number, status: number) {
  const result = await $API.dish.changeDishStatus(dishId, status)
  if (result.success) {
    $modal.msgSuccess('操作成功！')
    refreshList()
  } else {
    $modal.msgError('操作失败！')
  }
}

// 选择（多选）改变了
function selectionChange(dishList: Dish[]) {
  listState.multiSelectIds = [] // 重置
  dishList.forEach((dish: Dish) => listState.multiSelectIds.push(dish.id)) // 重新添加
}
// 点击了批量删除
async function batchDelete(dishIds: number[]) {
  if (dishIds == null || dishIds.length == 0) {
    $modal.msgWarning('未选择')
    return
  }
  const result = await $API.dish.deleteBatchDishes(dishIds)
  if (result.success) {
    $modal.msgSuccess('操作成功！')
    refreshList()
  } else {
    $modal.msgError('操作失败！')
  }
}
// 保存操作
function addOrEditDish(dishId?: number) {
  router.push({ path: '/dish/save', query: { id: dishId } })
}
// 查看或保存优先展示
const isViewPriorityDisplay = ref(false)
async function changeBetterDisplay(item: Dish) {
  const result = await $API.dish.changeBetterDisplayStatus(item.id, item.betterDisplay)
  if (!result.success) {
    $modal.msgError(result.message)
    item.betterDisplay = item.betterDisplay === BetterDisplayStatus.OPEN ? BetterDisplayStatus.CLOSE : BetterDisplayStatus.OPEN
  }
}
</script>

<style scoped lang="scss">
.tableBar {
  display: flex;
  justify-content: space-between;

  .tableLab {
    display: inline-flex;
    justify-content: end;
    align-items: center;

    span {
      display: inline-block;
      padding: 0 20px;
      font-size: 14px;
      cursor: pointer;
    }
  }
}

.condition-item {
  margin-right: 5px;
}
</style>
